from rest_framework import serializers
from .models import ApplicantList
from apps.sales_man.models import SalesMan, VisitApplicant
from core.tools.card_verify import verify_card
from core.tools.models import ShortMsg
from apps.utils.views import YouCardApi


class ApplyListSerializers(serializers.ModelSerializer):
    name = serializers.CharField(max_length=16, label="申请人姓名", help_text="申请人姓名", error_messages={
        "blank": "姓名不能为空",
        "max_length": "最长16个字符"
    })
    card = serializers.CharField(max_length=20, label="申请人身份证", help_text="申请人身份证", error_messages={
        "blank": "身份证不能为空",
        "max_length": "身份证最长20个字符"
    })
    tel = serializers.CharField(label="手机号", max_length=11, min_length=11, help_text="手机号", error_messages={
        "blank": "手机号不能为空",
        "max_length": "请正确填写手机号",
        "min_length": "请正确填写手机号"
    })
    salesman = serializers.IntegerField(label="登录用户", help_text="登录用户", error_messages={
        "blank": "请填写推荐人"
    })
    code = serializers.CharField(required=True, label="验证码", help_text="验证码", max_length=6, min_length=6,
                                 error_messages={
                                     "blank": "验证码不能为空",
                                     "max_length": "验证码只能是6位数字",
                                     "min_length": "验证码只能是6位数字"
                                 })

    class Meta:
        model = ApplicantList
        fields = ("name", "card", "tel", "salesman", "code")

    def validate_salesman(self, salesman):
        try:
            sales_obj = SalesMan.objects.get(id=salesman)

        except Exception as e:
            print(e)
            sales_obj = SalesMan.objects.get(tel="13366542267")
        return sales_obj.id

    def validate_card(self, card):
        # 验证身份证号
        if not verify_card(card):
            raise serializers.ValidationError("请检查身份证号")

    def validate_code(self, code):
        tel = self.initial_data["tel"]
        info = ShortMsg.objects.filter(code=code, tel=tel)
        if info.exists():
            info_obj = info.first()
            if info_obj.status:
                info_obj.status = False
                info_obj.save()
                return code
            else:
                raise serializers.ValidationError("此验证码已经使用过了")
        else:
            raise serializers.ValidationError("验证码不正确")

    def validate(self, attrs):
        del attrs["code"]
        return attrs


class VisitApplicantSerializers(serializers.ModelSerializer):
    visit_id = serializers.IntegerField(read_only=True)

    class Meta:
        model = VisitApplicant
        fields = ("visit_id", "product", "applicant")

    def validate_visit_id(self, visit_id):
        if visit_id:
            return visit_id
        else:
            raise serializers.ValidationError("参数错误")
